package com.sqx.modules.sign.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.sign.dao.GoldRecordsDao;
import com.sqx.modules.sign.dao.TbSigninDao;
import com.sqx.modules.sign.dao.TbSigninRewardDao;
import com.sqx.modules.sign.entity.GoldRecords;
import com.sqx.modules.sign.entity.TbSignin;
import com.sqx.modules.sign.entity.TbSigninReward;
import com.sqx.modules.sign.entity.vo.SigninStatus;
import com.sqx.modules.sign.service.TbSignInService;
import com.sqx.modules.task.dao.TbDailyTasksDao;
import com.sqx.modules.task.dao.TbUserTaskDao;
import com.sqx.modules.task.entity.TbDailyTasks;
import com.sqx.modules.task.entity.TbUserTask;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description：TODO
 * @author： qiao
 * @create： 2024/7/5 10:33
 */
@Service
public class TbSigninServiceImpl extends ServiceImpl<TbSigninDao, TbSignin> implements TbSignInService {

    @Autowired
    private TbSigninRewardDao tbSignInRewardDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private GoldRecordsDao goldRecordsDao;

    @Autowired
    private TbUserTaskDao tbUserTaskDao;

    @Autowired
    private TbDailyTasksDao tbDailyTasksDao;


    @Override
    public Result signIn(TbSignin tbSignin) {
        UserEntity user = userDao.selectById(tbSignin.getUserId());
        if (user == null) {
            return Result.error("该用户不存在或请重新登录");
        }
        LocalDate currentDate1 = LocalDate.now();
        // 判断日期如果大于今天，那就不让签到
        // 获取当前日期的开始时间
        LocalDate todayStart = currentDate1.atStartOfDay(ZoneId.systemDefault()).toLocalDate();
        java.sql.Date todayDate = new java.sql.Date(todayStart.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());
        if(tbSignin.getCheckInDate().isAfter(todayDate.toLocalDate())){
            return Result.error("未在签到日期，暂不能签到");
        }
        int count = baseMapper.selectCount(new LambdaQueryWrapper<TbSignin>().eq(TbSignin::getUserId, tbSignin.getUserId())
                .eq(TbSignin::getCheckInDate, currentDate1));
        if (count > 0) {
            return Result.error("今天已经签到过了");
        }
        // 获取当前日期
        Date currentDate = new Date();
        java.sql.Date yesterdaySqlDate = new java.sql.Date(DateUtils.addDays(currentDate, -1).getTime());
        // 判断昨天是否有签到记录
        TbSignin yesterdaySign = baseMapper.selectOne(new LambdaQueryWrapper<TbSignin>().eq(TbSignin::getUserId, tbSignin.getUserId())
                .eq(TbSignin::getCheckInDate, yesterdaySqlDate));
        // 连续签到
        if (yesterdaySign != null) {
            tbSignin.setConsecutiveDays(yesterdaySign.getConsecutiveDays() + 1);
            if (tbSignin.getConsecutiveDays() < 7) {
                TbSigninReward yesterdaySignReward = tbSignInRewardDao.selectOne(new LambdaQueryWrapper<TbSigninReward>()
                        .eq(TbSigninReward::getConsecutiveDays, yesterdaySign.getConsecutiveDays()));
                tbSignin.setRewardId(yesterdaySignReward.getId());
                tbSignin.setGoldNum(yesterdaySignReward.getGoldCoins());
            } else {
                TbSigninReward yesterdaySignReward = tbSignInRewardDao.selectOne(new LambdaQueryWrapper<TbSigninReward>()
                        .eq(TbSigninReward::getConsecutiveDays, 7));
                tbSignin.setRewardId(yesterdaySignReward.getId());
                tbSignin.setGoldNum(yesterdaySignReward.getGoldCoins());
            }
        } else {
            // 如果不是连续签到，重置为1
            tbSignin.setConsecutiveDays(1);
            TbSigninReward yesterdaySignReward = tbSignInRewardDao.selectOne(new LambdaQueryWrapper<TbSigninReward>()
                    .eq(TbSigninReward::getConsecutiveDays, 1));
            tbSignin.setRewardId(yesterdaySignReward.getId());
            tbSignin.setGoldNum(yesterdaySignReward.getGoldCoins());
        }
        tbSignin.setCheckInDate(String.valueOf(new java.sql.Date(currentDate.getTime()).toLocalDate()));
        tbSignin.setUserId(user.getUserId());
        tbSignin.setCreateTime(new Date());
        tbSignin.setSignStatus(1);
        // 根据天数查出相对应的奖励
        TbSigninReward tbSigninReward = tbSignInRewardDao.selectOne(new LambdaQueryWrapper<TbSigninReward>()
                .eq(TbSigninReward::getConsecutiveDays, tbSignin.getConsecutiveDays()));
        user.setTotalGold(user.getTotalGold() + tbSigninReward.getGoldCoins());
        userDao.updateById(user);
        if (baseMapper.insert(tbSignin) <= 0) {
            return Result.error("签到失败");
        }
        // 给签到用户添加记录及奖励金币
        GoldRecords goldRecords = new GoldRecords();
        goldRecords.setUserId(user.getUserId());
        goldRecords.setGoldChange(1);
        goldRecords.setRemark("签到奖励");
        goldRecords.setCreateTime(new Date());
        goldRecords.setRelatedId(tbSignin.getId());
        goldRecords.setGoldCoins(tbSigninReward.getGoldCoins());
        int result = goldRecordsDao.insert(goldRecords);
        if (result <= 0) {
            return Result.error("签到失败");
        }
        if (user.getInviterCode() != null && tbSignin.getTaskId() != null) {
//            LocalDate startTime = LocalDate.now();
//            int count = tbUserTaskDao.selectCount(new QueryWrapper<>(tbUserTaskDao.selectByCreateTime(tbSignin.getUserId(),
//                    startTime, tbSignin.getTaskId())));
//            if (count > 0) {
//                return Result.error("该用户今天已经完成过该任务");
//            }
            UserEntity inviter = userDao.selectOne(new LambdaQueryWrapper<UserEntity>()
                    .eq(UserEntity::getInvitationCode, user.getInviterCode()));
            if (inviter != null) {
                TbUserTask task = new TbUserTask();
                task.setUserId(tbSignin.getUserId());
                task.setTaskId(tbSignin.getTaskId());
                task.setState(1);
                task.setRewardClaimed(0);
                task.setCreateTime(new Date());
                tbUserTaskDao.insert(task);
                // 给签到用户的上级添加记录及奖励金币
                GoldRecords records = new GoldRecords();
                records.setUserId(inviter.getUserId());
                records.setGoldChange(1);
                records.setRemark("邀请的邀请人签到成功奖励");
                records.setCreateTime(new Date());
                records.setRelatedId(tbSignin.getId());
//                    TbDailyTasks tbDailyTasks = tbDailyTasksDao.selectById(tbSignin.getTaskId());
                records.setGoldCoins(tbSigninReward.getGoldCoins());
                int resultCode = goldRecordsDao.insert(records);
                if (resultCode <= 0) {
                    return Result.error("签到失败");
                }
                inviter.setTotalGold(inviter.getTotalGold() + tbSigninReward.getGoldCoins());
                userDao.updateById(inviter);
            }
        }
        return Result.success("签到成功");
    }

    @Override
    public Result getSignInList(Long userId) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("该用户不存在或请重新登录");
        }
        List<TbSignin> signinList = baseMapper.selectList(new LambdaQueryWrapper<TbSignin>()
                .eq(TbSignin::getUserId, userId)
                .orderByDesc(TbSignin::getCheckInDate));
        List<SigninStatus> signinStatusList = new ArrayList<>();
        // 初始化最大值
        int previousConsecutiveDays = Integer.MAX_VALUE;
        if (!signinList.isEmpty()) {
            for (TbSignin tbSignin : signinList) {
                SigninStatus signinStatus = new SigninStatus();
                signinStatus.setDate(tbSignin.getCheckInDate());
                signinStatus.setConsecutiveDays(tbSignin.getConsecutiveDays());
                signinStatus.setGoldNum(tbSignin.getGoldNum());
                if (tbSignin.getConsecutiveDays() < previousConsecutiveDays && tbSignin.getConsecutiveDays() >= 1) {
                    // 不是断签
                    signinStatus.setSignStatus(1);
                } else {
                    // 断签
                    signinStatus.setSignStatus(-1);
                }
                previousConsecutiveDays = tbSignin.getConsecutiveDays();
                signinStatusList.add(signinStatus);
            }
        }
        return Result.success().put("data", signinStatusList);
    }

    @Override
    public Result getListByRecords(Integer pageNum, Integer pageSize, Long userId) {
        UserEntity user = userDao.selectById(userId);
        if (user == null) {
            return Result.error("该用户不存在或请重新登录");
        }
        PageHelper.startPage(pageNum, pageSize);
        List<GoldRecords> recordsList = goldRecordsDao.selectList(new LambdaQueryWrapper<GoldRecords>()
                .eq(GoldRecords::getUserId, userId)
                .orderByDesc(GoldRecords::getCreateTime));
        return Result.success().put("data", new PageInfo<>(recordsList));
    }

    @Override
    public Result getSignInRewards() {
        List<TbSigninReward> list = tbSignInRewardDao.selectList(null);
        if (list != null && !list.isEmpty()) {
            return Result.success().put("data", list);
        }
        return Result.error("暂未找到该奖励");
    }
}
